package com.bds.wm.service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.bds.wm.model.User;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.impl.NutDao;
import org.springframework.stereotype.Service;

import com.bds.wm.model.common.Result;
import com.bds.wm.model.common.UserSession;
import com.bds.wm.utils.Const;
import com.bds.wm.utils.MD5Util;

/**
 * Created by guoyu on 2018/1/29.
 */
@Service
public class UserService {
    private org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(UserService.class);
    @Resource
    private NutDao taskDao;

    public Result login(HttpServletRequest request, String username, String password) {
        Result ret = new Result();
        try {
            HttpSession session = request.getSession();
            Condition c = Cnd.where("username", "=", username)
                    .and("password", "=", MD5Util.MD5(password)).and("status", "=", 1)
                    .and("client", "=", "yum");
            String session_id = session.getId();
            User u = taskDao.fetch(User.class, c);
            if (u != null) {

                // 0:待审批
                // 1:正常
                // 2:审批不通过
                // 3:禁用
                taskDao.update(User.class,
                        Chain.make("session_id", session_id),
                        Cnd.where("id", "=", u.getId()));
                UserSession userSession = new UserSession(u);
                request.getSession().setAttribute(UserSession.sessionKey, userSession);
                // ret.setData(userSession);
                ret.setResult(Const.SUC, "登录成功");
                LOGGER.info("[service]-[2]-用户登录成功-user_id=" + u.getId());
            } else {
                ret.setResult(Const.FAIL, "用户或者密码错误");
                LOGGER.info("[service]-[3]-用户或者密码错误-username=" + username);
            }
        } catch (Exception e) {
            ret.setResult(Const.FAIL, "检查用户名密码出错");
            LOGGER.warn("[service]-[33]-用户登录异常-username=" + username, e);
        }
        return ret;
    }

}
